#!conda install -c conda-forge folium=0.5.0 --yes
#import folium
#print('Folium installed and imported!')
import numpy as np # scientific computation
import pandas as pd # primary data structure library
import matplotlib.pyplot as plt #primary plotting stricture
import folium # map generator.
En esta página se muestra el procesamiento de la información correspondiente a los AP de WiFi gratuitos en la ciudad de México. El fin de esta página es crear herramientas visuales que muestren la conectividad en la ciudad, para evaluar y justificar el proyecto de Movilidad Inteligente: conectividad vehicular, a realizar por alumnos de posgrado y pregado del Tecnológico de Monterrey.
A continuación se muestra el proceso de procesamiento y visualización:
df = pd.read_csv('ubicacion-acceso-gratuito-internet-wifi-c5.csv')
df.head(3)
En este caso, primero se convierte todos los nombres de las columnas en cadenas de caracteres, en caso de que existieran números. Con el fin de homogeneizar la información
df.columns = list(map(str, df.columns))
df.dtypes
df.drop(['BOTON', 'ALTAVOZ', 'ESQUINA'], axis = 1, inplace = True)
df.describe(include=['object'])
Podemos ver que hay:
El paso siguiente es limpiar el dataframe, donde no haya WIFI Activo. También deependiendo de si tiene un incremento de 100Mbps será un mayor alcance, se puede hacer un ajuste posterior.
df['ESTATUS CONECTIVIDAD'].unique()
#df.drop(['REPORTE DE FALLA'], axis = 0).describe(include=['object'])
#df['ESTATUS CONECTIVIDAD'].replace('REPORTE DE FALLA', np.nan )
df.dropna(axis=0, inplace=True)
# reset index, because we droped two rows
df.reset_index(drop=True, inplace=True)
df
#Se eliminaron 200 antenas de Wi Fi con reporte de fallo aquÃ
dfCol = df.groupby(['COLONIA']).count().rename(columns={"DIRECCIÓN":"DIR"}).reset_index()
dfCol.head()
El siguiente paso, una vez filtrada nuestra base de datos es hacer visualización geoespacial. Para lograr esto, se recurre al archivo geojson de la ciudad de México, disponible en:
cdmx_geo = r'coloniascdmx.geojson'
# creating a numpy array of length 6 and has linear spacing from the minium total immigration to the maximum total immigration
threshold_scale = np.linspace(dfCol['DIR'].min(),
(dfCol['DIR'].max()-200),
6, dtype=int)
threshold_scale = threshold_scale.tolist() # change the numpy array to a list
threshold_scale[-1] = threshold_scale[-1] + 1 # make sure that the last value of the list is greater than the maximum immigration
mapa_cdmxCol = folium.Map(location=[19.4284700 , -99.1276600], zoom_start=12, tiles='Mapbox Bright')
mapa_cdmxCol.choropleth(
geo_data=cdmx_geo,
data=dfCol,
columns=['COLONIA', 'DIR'],
key_on='feature.properties.nombre',
threshold_scale=threshold_scale,
fill_color='BuPu',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Mapa Coroplexico WiFi Gratuito CDMX por Colonias',
reset=True
)
mapa_cdmxCol
dfAlc= df.groupby(['ALCALDIA']).count().rename(columns={"DIRECCIÓN":"DIR"}).reset_index()
dfAlc.head()
cdmx_geo = r'coloniascdmx.geojson'
mapa_cdmxAlc = folium.Map(location=[19.4284700 , -99.1276600], zoom_start=12,tiles='Mapbox Bright')
mapa_cdmxAlc.choropleth(
geo_data=cdmx_geo,
data=dfAlc,
columns=['ALCALDIA', 'DIR'],
key_on='feature.properties.alcaldia',
#threshold_scale=threshold_scale,
fill_color='BuPu',
fill_opacity=0.7,
line_opacity=0.5,
legend_name='Mapa Coroplexico WiFi Gratuito CDMX por AlcaldÃas',
reset=True
)
mapa_cdmxAlc
nummap = df.rename(columns={"LONGITUD":"x", "LATITUD":"y"}).drop(['TIPO DE POSTE'], axis=1)
nummap.head()
from folium import plugins
latitude=19.4284700
longitude=-99.1276600
# let's start again with a clean copy of the map of San Francisco
map_cdmx_num = folium.Map(location = [latitude, longitude], zoom_start = 12)
# instantiate a mark cluster object for the incidents in the dataframe
incidents = plugins.MarkerCluster().add_to(map_cdmx_num)
# loop through the dataframe and add each data point to the mark cluster
for lat, lng, label, in zip(nummap['y'], nummap['x'], nummap['ESTATUS CONECTIVIDAD']):
folium.Marker(
location=[lat, lng],
icon=None,
popup=label,
).add_to(incidents)
# display map
map_cdmx_num